package com.ruige.goreka.quartz;

import com.ruige.goreka.pojo.Service;
import com.ruige.goreka.pojo.StatusCode;
import com.ruige.goreka.service.GorekaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Configuration      //主要用于标记配置类，兼备Component的效果
@EnableScheduling //开启定时任务
public class QuartzDeleteJob {

    @Autowired
    private GorekaService gorekaService;

    //3.添加定时任务
// @Scheduled(cron = "0/5 * * * * ?")
    //或直接指定时间间隔，例如：5秒
    @Scheduled(fixedRate=30000)
    public void updateStatusOrDelete() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Service> serviceList = gorekaService.findAll();
        if (serviceList == null || serviceList.size() == 0) {
            System.out.println(new Date() + "  定时任务  INFO: 当前GOREKA暂无任何服务!" );
            return;
        }
        for (Service service : serviceList) {
            long last_time = service.getLast_update_time().getTime();
            long current_time = new Date().getTime();
            if (current_time-last_time>90000) {
                System.out.println(new Date() + "  定时任务  WARNING: " + service.getService_name() + "服务90s以上服务未续约,当前服务将被<剔除>!上次续约时间为:" + sdf.format(service.getLast_update_time()));
                gorekaService.delete(service);
                System.out.println(new Date() + "  定时任务  WARNING: 当前服务将被剔除成功!");
            } else if (current_time - last_time > 60000) {
                System.out.println(new Date()+"  定时任务  WARNING: "+service.getService_name()+"服务60s以上服务未续约,当前服务<异常>!上次续约时间为:"+sdf.format(service.getLast_update_time()));
                service.setStatus(StatusCode.STATUS_ERROR);
                gorekaService.updateStatusByServiceName(service);
            } else {
                System.out.println(new Date()+"  定时任务  INFO: <"+service.getService_name()+">服务<正常>!上次续约时间为:"+sdf.format(service.getLast_update_time()));
            }

        }

    }

}
